﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Text.RegularExpressions;

namespace Common.ValidHelper
{
    public class ExpiredValid
    {
        private string Email = AppSetting.ValidEmail;
        private string ApiUrl = AppSetting.ApiUrl;
        private readonly IHttpContextAccessor _context;
        private readonly ICache _cache;
        private HttpClient _client;

        public ExpiredValid(ICache cache, IHttpContextAccessor context)
        {
            _cache = cache;
            _client = new HttpClient();
            _context = context;
        }

        private ValidJsonData GetApiData()
        {
            string url = string.Empty;
            if (string.IsNullOrEmpty(Email))
            {
                string webhost = _context.HttpContext.Request.Host.Host;
                webhost = webhost.Match(@"[a-zA-Z0-9-]+.(com|org|net)?.(com|cn|net|org|biz|info|cc|tv|top|vip)");
                url = $"{ApiUrl}&email={webhost}";
            }
            else
            {
                url = $"{ApiUrl}&email={Email}";
            }
            var response = _client.GetStringAsync(url).Result;
            if (!string.IsNullOrEmpty(response))
            {
                var obj = response.ToObject<ValidJsonData>();
                obj.Email = Email;
                return obj;
            }
            return null;
        }

        /// <summary>
        /// 从缓存中读取，没有则会访问接口并存入缓存
        /// </summary>
        /// <returns></returns>
        public ValidJsonData GetValidData()
        {
            ValidJsonData result = null;
            var resultStr = _cache.Get<ValidJsonData>($"{SystemConstConfig.WebValidKey}");
            if (resultStr == null)
            {
                resultStr = GetApiData();
                if (resultStr != null)
                {
                    _cache.Set<ValidJsonData>($"{SystemConstConfig.WebValidKey}", resultStr, DateTimeOffset.Now.AddHours(24));
                    result = resultStr;
                }
            }
            else
            {
                result = resultStr;
            }
            return result;
        }
    }

}
